<?php

class TestMySqliQueryExecutor extends PHPUnitTest {
    /**
     * Variables
     */

    /**
     * @var MySqliDBConnection
     */
    protected $connection;

    /**
     * Tests
     */

    public function testMySqlQueryExecutorExecutesQueryStrings() {
        $query = 'SHOW DATABASES;';
        $queryExecutor = new MySqliQueryExecutor();

        $result = $queryExecutor->executeQueryString($query);

        $this->assertNotNull($result);
    }

    public function testMySqlQueryExecutorExecutesQueryObjects() {
        $this->connectToDatabase();
        $this->dropTestTable();
        $this->createTestTable();
        $this->insertDummyData();
        $fields = array('*');
        $table = 'example';
        $queryObject = new SelectQueryBuilder($fields, $table);
        $queryExecutor = new MySqliQueryExecutor();

        $result = $queryExecutor->executeQueryObject($queryObject);

        $resultArray = $result->fetch_all();
        $this->assertNotNull($result);
        $this->assertEquals(3, mysqli_num_rows($result));
        $this->assertEquals('ABC', $resultArray[0][1]);
        $this->assertEquals('DEF', $resultArray[1][1]);
        $this->assertEquals('XYZ', $resultArray[2][1]);
        $this->dropTestTable();
        $this->disconnectFromDatabase();
    }

    /**
     * Helpers
     */

    private function connectToDatabase() {
        $this->connection = new MySqliDBConnection();
        $this->connection->connect();
    }

    private function createTestTable() {
        $handler = $this->connection->getDBHandler();
        $query = 'CREATE TABLE example ( id INT, data VARCHAR(100) ); ';
        mysqli_query($handler, $query);
    }

    private function insertDummyData() {
        $handler = $this->connection->getDBHandler();
        $query1 = "INSERT INTO example VALUES (1, 'ABC');";
        $query2 = "INSERT INTO example VALUES (2, 'DEF');";
        $query3 = "INSERT INTO example VALUES (3, 'XYZ');";
        mysqli_query($handler, $query1);
        mysqli_query($handler, $query2);
        mysqli_query($handler, $query3);
    }

    private function dropTestTable() {
        $handler = $this->connection->getDBHandler();
        $query = 'DROP TABLE example;';
        mysqli_query($handler, $query);
    }

    private function disconnectFromDatabase() {
        $this->connection->disconnect();
        unset($this->connection);
    }

}